<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { ref } from 'vue';
import { Page, useVbenModal } from '@vben/common-ui';
import { useAccess } from '@vben/access';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getComponentApi, getMSDSdataApi, handleMSDSdataApi, printMSDSdataApi } from '#/api';
import { MdiAdd, MdiRefresh, MdiPrinter } from '@vben/icons';

import msdsForm from './form.vue';
import printForm from './print.vue';
import { confirmModal } from '#/components';

interface RowType {
  msdsNo: string;
  chemNameCn: string;
  component: string;
  fillDate: string;
}

const loadingV = ref(false); // 记录当前是否进入loading状态
const msdsFormRef = ref();
const { hasAccessByCodes } = useAccess();

const formOptions: VbenFormProps = {
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 默认展开
  collapsed: false,
  commonConfig: {
    colon: true,
    lableWidth: '120',
    componentProps: {
      class: 'w-full',
    },
  },
  fieldMappingTime: [['date', ['start', 'end']]],
  schema: [
    {
      component: 'ApiSelect',
      componentProps: {
        mode: 'multiple',
        placeholder: '请选择组成成分',
        allowClear: true,
        afterFetch: (data: { name: string; path: string }[]) => {
          return data.map((item: any) => ({
            label: item.name,
            value: item.name,
          }));
        },
        api: getComponentApi,
      },
      label: '组成成分', // $t('page.auth.forgetPassword'),
      fieldName: 'component',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入MSDS编号',
        addonBefore: 'WTC-',
      },
      fieldName: 'msdsNo',
      label: 'MSDS编号',
    },
  ],
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-3',
};

const gridOptions: VxeTableGridOptions<RowType> = {
  columns: [
    { fixed: 'left', type: 'checkbox', width: 75, title: '全选' },
    { title: '序号', type: 'seq', width: 50 },
    { field: 'msdsNo', title: 'MSDS编号' },
    { field: 'chemNameCn', title: '化学品名称' },
    { field: 'component', title: '组成成分' },
    { field: 'fillDate', title: '填报日期', width: 120, formatter: 'formatDate' },
    {
      fixed: 'right',
      width: 180,
      title: '操作',
      visible: true,
      slots: { default: 'action' },
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const values = formValues;
        // 将如果formValues.msdsNo不为空，则格式化为WTC-开头，数字位数不足四位，前面补0
        if (values.msdsNo) {
          values.msdsNo = 'WTC-' + values.msdsNo.toString().padStart(4, '0');
        }
        const result = await getMSDSdataApi({
          page: page.currentPage,
          pageSize: page.pageSize,
          ...values,
        });
        // 如果result.message不为ok或undefined，则使用message显示result.message
        if (result.message !== 'ok' && result.message !== undefined) {
          message.error(result.message);
        }
        return result;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    refreshOptions: {
      code: 'reload',
    },
    search: true,
    zoom: true,
  },
  customConfig: {
    mode: 'modal',
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  // 默认不显示搜索表单
  showSearchForm: false,
});

const [printModal, printmodalApi] = useVbenModal({
  connectedComponent: printForm,
  destroyOnClose: true,
});

/*==================================函数过程=========================================*/
// 打开新增表单
const handleAdd = async () => {
  loadingV.value = true;
  // 延迟0.5秒，确保全局loading生效，防止用户再次操作
  await new Promise((resolve) => setTimeout(resolve, 500));
  msdsFormRef.value.setData({
    isUpdate: false,
    gridApi,
  });
  msdsFormRef.value.open();
  await new Promise((resolve) => setTimeout(resolve, 500));
  loadingV.value = false;
};
// 打开编辑表单
const handleEdit = async (record: any) => {
  loadingV.value = true;
  // 延迟0.5秒，确保全局loading生效，防止用户再次操作
  await new Promise((resolve) => setTimeout(resolve, 500));
  msdsFormRef.value.setData({
    record,
    isUpdate: true,
    saveas: false,
    gridApi,
  });
  msdsFormRef.value.open();
  await new Promise((resolve) => setTimeout(resolve, 500));
  loadingV.value = false;
};
// 删除
const handleDelete = async (record: any) => {
  const confirmRes = await confirmModal('删除确认', '即将删除数据，是否继续？');
  if (!confirmRes) return;
  handleMSDSdataApi('delete', record.msdsNo).then(() => {
    message.success('删除成功');
    gridApi.reload();
  });
};
// 另存
const handleSaveas = async (record: any) => {
  loadingV.value = true;
  // 延迟0.5秒，确保全局loading生效，防止用户再次操作
  await new Promise((resolve) => setTimeout(resolve, 500));
  msdsFormRef.value.setData({
    record,
    isUpdate: true,
    saveas: true,
    gridApi,
  });
  msdsFormRef.value.open();
  await new Promise((resolve) => setTimeout(resolve, 500));
  loadingV.value = false;
};
// 打印
const handlePrint = async (record?: any) => {
  try {
    loadingV.value = true;
    message.loading({
      content: '数据加载中，请稍后...',
      duration: 0,
      key: 'beforePrint',
    });
    // 延迟0.5秒，确保全局loading生效，防止用户再次操作
    await new Promise((resolve) => setTimeout(resolve, 500));

    if (record) {
      const printValues = await printMSDSdataApi('print', record.msdsNo);
      // console.log('打印数据', printValues);
      if (printValues.docx && printValues.pdf) {
        // 打印
        message.success({
          content: '数据加载完成',
          key: 'beforePrint',
        });
        printmodalApi.setData({
          pdf: printValues.pdf,
        });
        printmodalApi.open();

        // 关闭loading
        loadingV.value = false;
      } else {
        message.error({
          content: '数据加载失败',
          key: 'beforePrint',
        });
      }
      return;
    }

    const selectedRows = await gridApi.grid.getCheckboxRecords();
    if (selectedRows.length > 0) {
      // gridApi.grid.removeCheckboxRow();
      message.success('打印成功');
    } else {
      message.info('请至少选择一行数据');
    }
  } finally {
    loadingV.value = false;
    message.destroy('beforePrint');
  }
};
// 刷新并返回第一页
const handleReload = async () => {
  gridApi.reload();
};
// 刷新当前页面
const handleRefresh = async () => {
  gridApi.query();
};
</script>

<template>
  <Page v-loading="loadingV" auto-content-height>
    <Grid>
      <template #action="{ row }">
        <Button class="px-1" type="link" @click="handlePrint(row)">打印</Button>
        <Button v-if="hasAccessByCodes(['msdsEdit'])" class="px-1" type="link" @click="handleEdit(row)">编辑</Button>
        <Button v-if="hasAccessByCodes(['msdsEdit'])" class="px-1" type="link" @click="handleSaveas(row)">另存</Button>
        <Button v-if="hasAccessByCodes(['msdsDelete'])" class="px-1" danger type="link" @click="handleDelete(row)"
          >删除</Button
        >
      </template>
      <template #toolbar-actions>
        <Button
          v-if="hasAccessByCodes(['msdsNew'])"
          class="mr-2 flex items-center justify-center"
          type="primary"
          @click="handleAdd"
        >
          <!-- 20像素大小的图标 -->
          <MdiAdd class="size-4" />
          新增
        </Button>
        <Button
          v-if="hasAccessByCodes(['msdsPrint'])"
          class="mr-2 flex items-center justify-center"
          type="primary"
          style="background-color: #ff9940"
        >
          <MdiPrinter class="size-4" />
          打印
        </Button>
        <Button
          class="mr-2 flex items-center justify-center"
          type="primary"
          style="background-color: #0bd092"
          @click="handleReload"
        >
          <MdiRefresh class="size-4" />
          刷新
        </Button>
      </template>
    </Grid>
    <msdsForm ref="msdsFormRef" />
    <printModal />
  </Page>
</template>
